package com.flying.tradingservice.service;

import com.flying.stockdetails.model.TradingCompany;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class TradingCompanyClient {
    private WebClient webClient;

    public TradingCompanyClient(WebClient.Builder builder) {
        this.webClient = builder.build();
    }

    public Flux<TradingCompany> findAllCompanies() {
        return webClient.get()
                .uri("http://localhost:18082/details")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToFlux(TradingCompany.class);
    }

    public Mono<TradingCompany> getTradingCompany(String ticker) {
        return webClient.get()
                .uri("http://localhost:18082/details/{ticker}", ticker)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(TradingCompany.class)
                .switchIfEmpty(Mono.error(new TickerNotFoundException("Unknown Ticker:" + ticker)));
    }
}
